﻿exports.DBUtils = {
    connection: null,
    setConnection: function (db) {
        this.connection = db;
    },
    getConnection: function (url,object) {
        var client = require('mongodb').MongoClient;
        var assert = require('assert');
        var ObjectId = require('mongodb').ObjectID;
        var _set_connection = this.setConnection;
        var _call_obj = this;
        //var url = 'mongodb://"+ip+":"+port+"/' + dbName;
        var p = new Promise(function (resolve, reject) {
            client.connect(url, function (err, db) {
                if (err) {
                    reject(err);
                } else {
                    resolve({ result: db, object: object });
                }
            });
        });
        return p;     
    },
    insert: function (db, table, data, object) {
        var p = new Promise(function (resolve, reject) {
            db.collection(table).insert(data, function (err) {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    resolve(object);
                }
            });
        });
        return p;
    },
    find: function (db, table, query, object) {
        var p = new Promise(function (resolve, reject) {
            db.collection(table).find(query).then(function (result) {
                resolve({ result: result, object: object });
            }).catch(function (err) {
                reject(err)
            });
        });
        return p;       
    },
    close: function (db){
        db.close();
    }
}